package com.xiguaji.tiktok.task.blogger.event;

import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import com.gugee.tiktok.common.model.dal.blogger.BloggerMainRepository;
import com.gugee.tiktok.common.model.mysql.Blogger;
import com.xiguaji.boot.eventbus.Event;
import com.xiguaji.boot.eventbus.IEventListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class SaveBloggerMainEventListener implements IEventListener<SaveBloggerMainEventListener.SaveBloggerMainEvent> {
    @Autowired
    BloggerMainRepository bloggerMainRepository;

    @Override
    @AllowConcurrentEvents
    @Subscribe
    public void handle(SaveBloggerMainEvent event) {
        //过滤在bloggerMain表中不存在的播主
        List<Blogger> bloggers = event.bloggers.stream().
                filter(blogger -> !bloggerMainRepository.existsByoUid(blogger.getOUid()))
                .collect(Collectors.toList());

        if (CollectionUtils.isEmpty(bloggers)) return;

        bloggerMainRepository.batchInsert(bloggers,"SaveBloggerMainEventListener");
    }

    public static class SaveBloggerMainEvent extends Event {

        public SaveBloggerMainEvent(Event event, List<Blogger> bloggers) {
            super(event, "SaveBloggerMainFollower");
            this.bloggers = bloggers;
        }

        private List<Blogger> bloggers;
    }
}
